package com.sailfish.template.infra.repository.iam.impl;

import com.sailfish.template.infra.common.constants.ResponseCode;
import com.sailfish.template.infra.common.constants.ResponseEntity;
import com.sailfish.template.infra.exception.FeignClientException;
import com.sailfish.template.infra.feign.SailfishIamClient;
import com.sailfish.template.infra.feign.vo.IamProjectVO;
import com.sailfish.template.infra.repository.iam.SteamIamRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Objects;

/**
 * @author XIAXINYU3
 * @date 2021/11/9
 */
@Slf4j
@Repository
public class SteamIamRepositoryImpl implements SteamIamRepository {
    @Autowired
    SailfishIamClient sailfishIamClient;

    @Override
    public IamProjectVO createProject(Long organizationId, IamProjectVO iamProject) {
        String errorCode = "project.steam.create.error";
        ResponseEntity<IamProjectVO> responseEntity = null;
        try {
            responseEntity = sailfishIamClient.createProjectWithin(organizationId, iamProject);
        } catch (Exception e) {
            throw new FeignClientException(errorCode, e);
        }

        checkResponse(errorCode, responseEntity);

        IamProjectVO result = responseEntity.getData();
        if (Objects.isNull(result.getId())) {
            throw new FeignClientException(errorCode);
        }
        return result;
    }

    private void checkResponse(String code, ResponseEntity<?> responseEntity) {
        if (Objects.isNull(responseEntity) || !Objects.equals(responseEntity.getCode(), ResponseCode.SUCCESS)) {
            log.error("调用远程服务异常，{}", responseEntity.getMessage());
            throw new FeignClientException(code);
        }
    }
}
